//
//  TCLiveUSERTabar.swift
//  onemeetingmac
//
//  Created by 张衡 on 2020/3/2.
//  Copyright © 2020 onemeeting. All rights reserved.
//

import Foundation

class TCLiveUSERTabar: NSView {
    
    var uBtns:[ZHButton] = []
    
    var btnTitles:([String],[String]) = (["全体静音","更多"],["举手","静音","独立弹出"])
    
    var isJoin:Bool = false {
        didSet {
            let btns = self.initSubBtns(inView: conner, isJoin: self.isJoin)
            self.uBtns = btns
        }
    }
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    convenience init(isJoin:Bool) {
        self.init()
        self.isJoin = isJoin
        self.setupUI()
        self.addNot()
    }
    
    func addNot() {
        NotificationCenter.default.addObserver(self, selector: #selector(userStatuChange(not:)), name: MTUserStateNotification, object: nil)
    }
    
    func setupUI() {
        self.addSubview(conner)
        conner.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        self.addSubview(lineV)
        lineV.snp.makeConstraints { (make) in
            make.width.top.centerX.equalToSuperview()
            make.height.equalTo(1)
        }
        
        let btns = self.initSubBtns(inView: conner, isJoin: self.isJoin)
        self.uBtns = btns
    }
    
    lazy var conner: NSView = {
        let view = NSView()
        return view
    }()
    
    lazy var lineV: NSView = {
        let view = NSView()
        view.wantsLayer = true
        view.layer?.backgroundColor = color_gray(88).cgColor
        return view
    }()
    
    func getBtnsWidth(ts:[String]) -> CGFloat {
        var wid:CGFloat = 0
        for (_,t) in ts.enumerated() {
            let tw = t.ga_width(font: 14)+30
            wid+=tw
        }
        return wid
    }
    
    func checkTitles() -> ([String],[String]) {
        let isStand = Td.sh().isStand ? "回到主窗口":"独立弹出"
        let isHandUp = Td.sh().lc.isHandUp ? "放下":"举手"
        let isMute = Td.sh().lc.isMute ? "解除":"静音"
        let downMic = "下麦"
        self.btnTitles.1 = [isHandUp,isMute,downMic,isStand]
        
        let allMute = Td.sh().cloud.isALLMute ? "全体静音解除":"全体静音"
        let down = "全部放手"
        let more = "更多"
        self.btnTitles.0 = [allMute,down,more]
        
        return btnTitles
    }
    
    func initSubBtns(inView:NSView,isJoin:Bool) -> [ZHButton] {
        for (_,val) in self.uBtns.enumerated() {
            val.removeFromSuperview()
        }
        
        let btnTitles = self.checkTitles()
        let selfWidth = inView.frame.width==0 ?kTRTCUserWidth:inView.frame.width
        let titls = isJoin ? btnTitles.1:btnTitles.0
        let space = (selfWidth-self.getBtnsWidth(ts: titls))/CGFloat(titls.count+1)
        var uBtn:[ZHButton] = []
        
        for (inx,val) in titls.enumerated() {
            let btn = ZHButton()
            btn.zh_title = val
            btn.zh_font = NSFont.systemFont(ofSize: 12)
            btn.zh_color = color_dark160
            btn.hoverColor = color_main108
            btn.hasBorder = true
            btn.zh_cornerRadius = 3.0
            btn.zh_backgroundColor = color_dark70
            btn.backgroundHoverColor = color_dark160
            btn.tag = 100+inx
            btn.target = self
            btn.action = #selector(selectBtnAction(senber:))
            inView.addSubview(btn)
            uBtn.append(btn)
            let width = val.ga_width(font: 14)+30
            btn.snp.makeConstraints { (make) in
                make.width.equalTo(width)
                make.centerY.equalToSuperview()
                make.height.equalTo(22)
                if inx == 0 {
                    make.left.equalTo(space)
                }else {
                    make.left.equalTo(uBtn[inx-1].snp.right).offset(space)
                }
                
            }
        }
        return uBtn
    }

    func createFiltersMenuItems() -> [NSMenuItem] {
        var item:[NSMenuItem] = []
        let stand = Td.sh().isStand ? "回到主窗口":"独立弹出"
        let menuNames = [stand]
        for (inx,val) in menuNames.enumerated() {
            let menu = NSMenuItem(title: val, action: #selector(applyImageFilter(_:)), keyEquivalent: "")
            menu.tag = inx
            menu.state = .off
            menu.target = self
            menu.isEnabled = true
            item.append(menu)
        }
        return item
    }
     
    @objc func applyImageFilter(_ item:NSMenuItem) {
        switch item.tag {
        case 0:
            Td.sh().isStand = !Td.sh().isStand
            let isStand = Td.sh().isStand
            item.title = isStand ? "独立弹出":"回到主窗口"
            self.setStand(isok:isStand)
        default:
            break
        }
    }
    
    @objc func muteALLBtnAction(senber:ZHButton) {
        Td.sh().cloud.isALLMute = !Td.sh().cloud.isALLMute
        let isok = Td.sh().cloud.isALLMute
        IMcmd.shared.allMute(isok: isok)
        let title = isok ? "全体静音解除":"全体静音"
        senber.zh_title = title
    }
    
    @objc func moreBtnAction(senber:ZHButton)  {
        let frame = senber.frame
        let menuOrigin = senber.superview?.convert(NSPoint.init(x: frame.origin.x, y: frame.origin.y-8), to: nil)
        let event = NSEvent.mouseEvent(with: NSEvent.EventType.leftMouseDown,
                           location: menuOrigin!,
                           modifierFlags: NSEvent.ModifierFlags.control,
                           timestamp: 0,
                           windowNumber: senber.window!.windowNumber,
                           context: senber.window?.graphicsContext,
                           eventNumber: 0,
                           clickCount: 1,
                           pressure: 1)
        
        let menu = NSMenu.init(title: "menu")
        self.createFiltersMenuItems().forEach { (item) in
            menu.addItem(item)
        }
        menu.needsUpdate()
        menu.isDark = true
        NSMenu.popUpContextMenu(menu, with: event!, for: senber)
    }
    
    func downMic() {
        let asV = KlViewController.init(title: "我要下麦", massage: "你确定要下麦吗？", buttomTitles: ["确认","取消"]) { (index, controller) in
            if index == 0 {
                TrtcEngine.switchRoleTo(isAdc: true)
            }
        } navBlock: { }
        let window = NSWindow.init(contentViewController: asV)
        window.makeKeyAndOrderFront(nil)
    }
    
    @objc func selectBtnAction(senber:ZHButton) {
        if self.isJoin {
            switch senber.tag {
            case 100:
                Td.sh().lc.isHandUp = !Td.sh().lc.isHandUp
                let isHandUp = Td.sh().lc.isHandUp
                MTNot.postNotHandUp(isok: isHandUp)
                IMcmd.shared.handUp(isok: isHandUp)
            case 101:
                Td.sh().lc.isMute = !Td.sh().lc.isMute
                MTNot.postNotMute()
            case 102:
                self.downMic()
            case 103:
                self.touchStand(senber: senber)
            default:
                break
            }
        }else {
            switch senber.tag {
            case 100:
                self.muteALLBtnAction(senber: senber)
            case 101:
                IMcmd.shared.downAllHand()
                MTNot.postNotAllHandUp()
            case 102:
                self.moreBtnAction(senber: senber)
            default:
                break
            }
        }
    }
    
    func touchStand(senber:ZHButton) {
        Td.sh().isStand = !Td.sh().isStand
        let isStand = Td.sh().isStand
        senber.zh_title = isStand ? "独立弹出":"回到主窗口"
        self.setStand(isok: isStand)
    }
    
    func setStand(isok:Bool) {
        if isok {
            let vc = TCLiveUSEREngViewController.init(isStand: true)
            let window = NSWindow.init(contentViewController: vc)
            window.orderFront(nil)
            MTNot.postHasUser(isok: false)
        }else {
            if let window = NSWindow.lrfind(anyClass: TCLiveUSEREngViewController.classForCoder()) {
                window.close()
            }
            MTNot.postHasUser(isok: true)
        }
    }
}


//MARK:- 通知
extension TCLiveUSERTabar {
    @objc func userStatuChange(not:Notification) {
        guard let mode = not.object as? UserMode else {
            return
        }
        
        if self.isJoin==true && mode.userId==nil {
            if let isMute = mode.isMute {
                if self.isJoin {
                    self.uBtns[1].zh_title = isMute ? "解除":"静音"
                }
            }
            if let isHandUp = mode.isHandUp {
                if self.isJoin {
                    self.uBtns[0].zh_title = isHandUp ? "放下":"举手"
                }
            }
        }
    }
}
